package com.amap.config;

import com.amap.client.AmapMerchantSdkClient;
import com.amap.http.HttpClientStrategy;
import com.amap.http.impl.AmapRestTemplateHttpClient;
import com.amap.sign.SignStrategy;
import com.amap.sign.SignVerifier;
import com.amap.sign.impl.DefaultSignVerifier;
import com.amap.sign.impl.RSA2SignStrategy;
import com.amap.template.AmapClientTemplate;
import com.amap.template.AmapServiceTemplate;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * 自动配置
 * @author liuyi
 * @since 2025/10/31 9:15
 */
@Configuration
@EnableConfigurationProperties({AmapSdkConfig.class, AmapMerchantConfig.class})
public class AmapAutoConfig {
    @Bean
    @ConditionalOnMissingBean({SignVerifier.class})
    @Primary
    public SignVerifier signVerifier(AmapSdkConfig sdkConfig) {
        return new DefaultSignVerifier(sdkConfig.getAmapPublicKey());
    }

    @Bean
    @Primary
    @ConditionalOnMissingBean({AmapMerchantSdkClient.class})
    public AmapMerchantSdkClient amapMerchantSdkClient(AmapMerchantConfig amapMerchantConfig) {
        return new AmapMerchantSdkClient(amapMerchantConfig);
    }

    @Bean
    @Primary
    @ConditionalOnMissingBean({SignStrategy.class})
    public SignStrategy signStrategy() {
        return new RSA2SignStrategy();
    }

    @Bean
    @Primary
    @ConditionalOnMissingBean({HttpClientStrategy.class})
    public HttpClientStrategy httpClientStrategy() {
        return new AmapRestTemplateHttpClient();
    }

    @Bean
    @Primary
    @ConditionalOnMissingBean({AmapClientTemplate.class})
    public AmapClientTemplate amapClientTemplate(AmapMerchantConfig merchantConfig, SignStrategy signStrategy, HttpClientStrategy httpClient) {
        return new AmapClientTemplate(merchantConfig, signStrategy, httpClient);
    }

    @Bean
    @Primary
    @ConditionalOnMissingBean({AmapServiceTemplate.class})
    public AmapServiceTemplate amapServiceTemplate(SignVerifier signVerifier, AmapSdkConfig sdkConfig) {
        return new AmapServiceTemplate(signVerifier, sdkConfig.isSignEnabled());
    }
}
